package com.qd.videorecorder;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.qd.videorecorder.util.RecordMixMp3;
import com.qd.videorecorder.util.SimpleLame;
import com.qd.videorecorder.util.ToastUtils;
import com.qd.videorecorder.view.BottomArriveView;
import com.qd.videorecorder.view.CustomToast;
import com.qd.videorecorder.view.LyricView;
import com.qd.videorecorder.view.ProgressBarPopup;

public class SingAndSMusic extends FinalActivity {
	
	private String tag = "";

	@ViewInject(id=R.id.main_btn_below , click="viewClick") Button main_btn_below;
	@ViewInject(id=R.id.topbar_title ) TextView topbar_title;
	//录音时间显示
	@ViewInject(id=R.id.tv_recod_time) TextView tv_time;
	@ViewInject(id=R.id.mylrc) LyricView mylrc;
	
	@ViewInject(id=R.id.btn_more, click="viewClick") Button btn_more;
	@ViewInject(id=R.id.btn_finish_record, click="viewClick") Button btn_finish_record;
	@ViewInject(id=R.id.btn_volume, click="viewClick") Button btn_volume;
	//文件名
	private String filenames = null;
	//设置文件名的编辑框
//	private EditText fileNameEditText = null;
	private boolean iscancel = false;
	//控制按钮
//	private Button startRecord, stopRecord, decodeMp3, saveMixRecord, playRecord;
	//录音状态
	private boolean starting = false;
	//播放状态
	private boolean playing = false;
	
	private boolean finish = false;
	
	private boolean bz = false;
	
	private AudioRecord audioRecord = null;
	private RecordTask rt = null;
	
	private String filePath = "";
	private String bzPath = "";
	private String pcmPath = "";
	private PlayTask player;    
	private String bgtime = "";
	private int bgtimetmp = 0;
	
	static {
		System.loadLibrary("mad");  
	}  
    
   /**
    * 录制频率，单位hz.这里的值注意了，写的不好，可能实例化AudioRecord对象的时候，会出错。我开始写成11025就不行。这取决于硬件设备
    * 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
    */
   private int sampleRateInHz = 44100;
   /**
    *  设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
    */
   private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;   
   
   /**
    * 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持。
    */
   private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
	
   public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.singandsmusic);
		
		Intent intent = getIntent();
		
		String title = intent.getStringExtra("title");
		tag = intent.getStringExtra("tag");
		bzPath = intent.getStringExtra("filepath");
		pcmPath = intent.getStringExtra("pcmPath");
		
		if(title==null){
			title = getResources().getString(R.string.app_name);
		}
		
		topbar_title.setText(title);
		
		//文件保存路径
		filePath = RecordMixMp3.getLocalPath() + "/music/";

//		startRecord = (Button) findViewById(R.id.startRecord);
//		stopRecord = (Button) findViewById(R.id.stopRecord);
//		decodeMp3 = (Button) findViewById(R.id.decodeMp3);
//		saveMixRecord = (Button) findViewById(R.id.saveMixRecord);
//		playRecord = (Button) findViewById(R.id.playRecord);
		
//		startRecord.setOnClickListener(listener);
//		stopRecord.setOnClickListener(listener);
//		decodeMp3.setOnClickListener(listener);
//		saveMixRecord.setOnClickListener(listener);
//		playRecord.setOnClickListener(listener);
		
		startRecord();
		
	}
	
	public void viewClick(View v){
		switch (v.getId())
			{
			case R.id.main_btn_below:
				starting = false;
				finish();
				break;
		
			case R.id.btn_finish_record:
				
				if(bz){
					showDialogNewName(3);
				}else{
					
					if(iscancel){
						if(bz){
							showDialogNewName(3);
						}else{
							showDialogNewName(2);
						}
					}else{
						starting = false;
						finish = true;
						
						if(mPlayer!=null&&mPlayer.isPlaying()){
							mPlayer.stop();
		    			}
					}
				}
				
				break;
			case R.id.btn_more:
				BottomArriveView bottomArriveView = new BottomArriveView(this);
				bottomArriveView.showAtLocation(btn_more, Gravity.BOTTOM, 0, 0);
				break;
			case R.id.btn_volume:
				if(tag!=null&&tag.equals("bz")){
					int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
					int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); 
					btn_volume.measure(w, h); 
					int height =btn_volume.getMeasuredHeight(); 
					int width =btn_volume.getMeasuredWidth(); 
					
					ProgressBarPopup progressBarPopup = new ProgressBarPopup(this);
					progressBarPopup.showAtLocation(btn_volume, Gravity.BOTTOM | Gravity.RIGHT, width/3, height + (height/3));
				}
				break;
			default:
				break;
			}
	}
	
	private MediaPlayer mPlayer;
	private int INTERVAL = 45;// 歌词每行的间隔
	
	private void playBg(){
		
		try {
			if(tag!=null&&tag.equals("bz")){
				if(mPlayer==null){
					mPlayer = new MediaPlayer();
				}
				if(mPlayer != null&&!mPlayer.isPlaying()){
					mPlayer.release();
					mPlayer = null;
					mPlayer = MediaPlayer.create(this, Uri.parse(bzPath));
					System.out.println("播放背景音");
					mPlayer.start();
//					mylrc.setOffsetY( mylrc.SelectIndex(mPlayer.getCurrentPosition())* (mylrc.getSIZEWORD() + INTERVAL - 1));
					bgtimetmp = mPlayer.getDuration()/1000;
					
					if(bgtimetmp<60){
						if(bgtimetmp<10){
							bgtime = "00:0"+bgtimetmp;
						}else{
							bgtime = "00:"+bgtimetmp;
						}
					}else{
						double bgmin = bgtimetmp/60.0;
						int bgimin = (int)bgmin;
						int bgsec = bgtimetmp%60;
						
						if(bgimin<10){
							bgtime = "0"+bgimin;
						}else{
							bgtime = ""+bgimin;
						}
						
						if(bgsec<10){
							bgtime = bgtime+":0"+bgsec;
						}else{
							bgtime = bgtime+":"+bgsec;
						}
					}
					
				}else{
					System.out.println("停止播放播放背景音");
					mPlayer.stop();
				}
				
				mPlayer.setOnCompletionListener(new OnCompletionListener() {
					
					@Override
					public void onCompletion(MediaPlayer mp) {
						// TODO Auto-generated method stub
						mylrc.SetTextSize();
						mylrc.setOffsetY(200);
					}
				});
			}
//			}else{
//				ToastUtils.showShort(RecordActivity.this, "您还没有选择背景音乐");
//			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	class runable implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {

				try {
					Thread.sleep(100);
					if (mPlayer.isPlaying()) {
//						mylrc.setOffsetY(mylrc.getOffsetY()	- mylrc.SpeedLrc());
						mylrc.setOffsetY(mylrc.getOffsetY()	- mylrc.SpeedLrc());
						mylrc.SelectIndex(mPlayer.getCurrentPosition());
						mHandler.post(mUpdateResults);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	Handler mHandler = new Handler();
	Runnable mUpdateResults = new Runnable() {
		public void run() {
			mylrc.invalidate(); // 更新视图
		}
	};
	
	public void reset() {
		// TODO Auto-generated method stub
		
		starting = false;
		
		while (audioRecord!=null&&audioRecord.getRecordingState()==AudioRecord.RECORDSTATE_RECORDING) {
			
		}
		
		rt.cancel(true);
		
		System.out.println(rt.isCancelled());
		
		if(mPlayer!=null){
			mPlayer.stop();
		}
		
		startRecord();
		
	}
	
	private void startRecord(){
		starting = true;
		
		if(tag!=null&&tag.equals("bz")){
			mylrc.setVisibility(View.VISIBLE);
			SerchLrc();
			playBg();
			new Thread(new runable()).start();
		}else{
			mylrc.setVisibility(View.GONE);
		}
		
		Thread thread = new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				
				recordToPCM();
				
			}
			
		};
		
		thread.start();
	}
	
	public void SerchLrc() {
		String lrc = bzPath;
		lrc = lrc.substring(0, lrc.length() - 4).trim() + ".lrc".trim();
		mylrc.read(lrc);
		System.out.println("SetTextSize");
		mylrc.SetTextSize();
		mylrc.setOffsetY(50);
	}
	
	private void recordToPCM(){
		
		//初始化录音控件
		int bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
		audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC , sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes);
		byte[] audioData = new byte[bufferSizeInBytes];
		int offsetInBytes = 0;
		int sizeInBytes = bufferSizeInBytes;
		System.out.println("SampleRate:"+audioRecord.getSampleRate());
		try {
			File audioFile = new File(filePath+"pcm/source.pcm");
			//初始化输出流
			DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(audioFile)));
			//开始录音
			audioRecord.startRecording();
			rt=new RecordTask();
			rt.execute();
			//判断是否在录音状态
			while (starting) {
				int size = audioRecord.read(audioData, offsetInBytes, sizeInBytes);
				//写入PCM文件
				dos.write(audioData, 0, size);
				dos.flush();
			}
			
			//关闭录音
			if(audioRecord!=null){
				if(audioRecord.getState()==AudioRecord.STATE_INITIALIZED){
					//关闭录音
					audioRecord.stop();
					audioRecord.release();
					Log.d(getClass().getName(), "audioRecord-->>release");
				}
			}
			//关闭写入文件操作
			dos.close();
			
			if(tag!=null&&tag.equals("bz")&&finish){
				handler.sendEmptyMessage(10002);
			}else if(finish){
				handler.sendEmptyMessage(10003);
			}else if(bz){
				handler.sendEmptyMessage(2);
			}else{
				audioFile.delete();
			}
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void showDialogNewName(final int ddd){
		try{
			
			final Dialog dialog = new Dialog(SingAndSMusic.this, R.style.dialog);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.show();
			dialog.setCancelable(true);
			Window window = dialog.getWindow();
			window.setGravity(Gravity.CENTER);
			window.setContentView(R.layout.save_record_new_name);
//			window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			final EditText et_file_name = (EditText)window.findViewById(R.id.et_file_name);
			
			et_file_name.setHint("文件名称请以非数字开头");
			et_file_name.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					try {
						int startStr = s.charAt(0);
						if(startStr<48 || startStr>57){
							System.out.println("改变后startStr:"+startStr);
						}else{
							et_file_name.setText("");
							ToastUtils.showShort(SingAndSMusic.this, "文件名称请以非数字开头");
						}
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
				}
			});
			
			Button btn_save = (Button)window.findViewById(R.id.btn_save);
			btn_save.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v)
				{
					// TODO Auto-generated method stub
					//用户自定义文件名
					filenames = et_file_name.getText().toString();
					//创建一个文件
					File file=new File(filePath+"record/"+filenames+".mp3");
					if(filenames==null||filenames.equals("")){
						handler.sendEmptyMessage(10000);
					}else{
						if(!file.exists()){
							dialog.dismiss();
							distoryDialog(dialog);
							if(ddd==1){
								handler.sendEmptyMessage(1);
								new Thread(){
									
									public void run() {
										int r = mix2PCMToPCM2(filePath+"pcm/source.pcm", pcmPath ,filePath+"pcm/mix.pcm");
										if(r==0){
											int bufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat); 
//													String fileName = ""+DateFormat.format("yyyyMMddhmmss", System.currentTimeMillis());
											int rs = SimpleLame.convert(filePath+"pcm/mix.pcm", filePath+"record/"+filenames+".mp3", bufferSize);
											System.out.println("rs:"+rs);
											if(rs==0){
												Intent intent = new Intent();
												intent.setClass(SingAndSMusic.this, RecordLocalMusic.class);
												startActivity(intent);
												finish();
												handler.sendEmptyMessage(0);
											}
										}
									}
								}.start();
							}else if(ddd==2){
								handler.sendEmptyMessage(1);
								new Thread(){
									public void run() {
										int bufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat); 
//												String fileName = ""+DateFormat.format("yyyyMMddhmmss", System.currentTimeMillis());
										int r = SimpleLame.convert(filePath+"pcm/source.pcm", filePath+"record/"+filenames+".mp3", bufferSize);
										System.out.println("r:"+r);
										if(r==0){
											Intent intent = new Intent();
											intent.setClass(SingAndSMusic.this, RecordLocalMusic.class);
											startActivity(intent);
											finish();
											handler.sendEmptyMessage(0);
										}
									}
								}.start();
							}else{
								handler.sendEmptyMessage(1);
								new Thread(){
									
									public void run() {
										int r = mix2PCMToPCM2(filePath+"pcm/source.pcm", pcmPath ,filePath+"pcm/mix.pcm");
										if(r==0){
											int bufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat); 
//											String fileName = ""+DateFormat.format("yyyyMMddhmmss", System.currentTimeMillis());
											int rs = SimpleLame.convert(filePath+"pcm/mix.pcm", filePath+"record/"+filenames+".mp3", bufferSize);
											System.out.println("rs:"+rs);
											if(rs==0){
												Intent intent = new Intent();
												intent.setClass(SingAndSMusic.this, RecordLocalMusic.class);
												startActivity(intent);
												finish();
												handler.sendEmptyMessage(0);
											}
										}
									};
									
								}.start();
							}
								
						}else{
							handler.sendEmptyMessage(10001);
						}
					}
				
				}
			});
			
			Button btn_cancel = (Button)window.findViewById(R.id.btn_cancel);
			btn_cancel.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v)
				{
					// TODO Auto-generated method stub
					iscancel =  true;
					dialog.dismiss();
				}
			});
			/*
			fileNameEditText = new EditText(this);
			fileNameEditText.setHint("文件名称请以非数字开头");
			fileNameEditText.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub
				}
				
				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					try {
						int startStr = s.charAt(0);
						if(startStr<48 || startStr>57){
							System.out.println("改变后startStr:"+startStr);
						}else{
							fileNameEditText.setText("");
							ToastUtils.showShort(SingAndSMusic.this, "文件名称请以非数字开头");
						}
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
				}
			});
			//如果获得的字节数组不为空则保存
			//System.out.println("成功了");
			new AlertDialog.Builder(this)
			.setTitle("请输入文件名称")
//				.setMessage("文件将保存在"+localFilepath+Constants.EXTERPATH_RECORD)
			.setIcon(android.R.drawable.ic_dialog_info)
			.setView( fileNameEditText ).setPositiveButton("确定", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
										
								}
							})
				     .setNegativeButton("取消", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							iscancel =  true;
							distoryDialog(dialog);
						}
						
					}).show();*/
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	private void keepDialog(DialogInterface dialog) {  
        try {  
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");  
            field.setAccessible(true);  
            field.set(dialog, false);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
	
	private void distoryDialog(DialogInterface dialog){  
        try {  
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");  
            field.setAccessible(true);  
            field.set(dialog, true);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }   
    }  
	
	ProgressDialog progressDialog;
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what)
				{
				case 0:
					if(progressDialog!=null){
						progressDialog.dismiss();
					}
					CustomToast.showToast(SingAndSMusic.this, "录音已保存", 1000);
					break;
				case 1:
					progressDialog = new ProgressDialog(SingAndSMusic.this);
					progressDialog.setMessage("正在保存...");
					progressDialog.setCancelable(false);
					progressDialog.show();
					break;
				case 2:
					CustomToast.showToast(SingAndSMusic.this, "录音完成", 1000);
					break;
				case 10000:
					CustomToast.showToast(SingAndSMusic.this, "请输入正确的文件名称", 1000);
					break;
				case 10001:
					CustomToast.showToast(SingAndSMusic.this, "文件已存在，请重新输入", 1000);
					break;
				case 10002:
					showDialogNewName(1);
					break;
				case 10003:
					showDialogNewName(2);
					break;
				default:
					break;
				}
			
		}
		
	};
	
	/*进行图片时钟显示*/
    class RecordTask extends AsyncTask<Void, Integer, Void>{
    	
		@Override  
        protected Void doInBackground(Void... arg0) {
            
            try {
            	//记录进度
    			int progress = 0;
                while (starting)
                {                	
                	publishProgress(new Integer(progress)); //向UI线程报告当前进度
                	progress++;
                	Thread.sleep(1000);    
                }
                //更新状态   
            } catch (Exception e) {
            	e.printStackTrace();
            }
            return null;
        }
        //当在上面方法中调用publishProgress时，该方法触发,该方法在UI线程中被执行   
        @Override
		protected void onProgressUpdate(Integer...progress){
//            stateView.setText("正在录音");
            int sj=progress[0];

			String time = "";
			
			if(sj<60){
				if(sj<10){
					time = "00:0"+sj;
				}else{
					time = "00:"+sj;
				}
			}else{
				double dmin = sj/60.0;
				int imin = (int)dmin;
				int sec = sj%60;
				
				if(imin<10){
					time = "0"+imin;
				}else{
					time = ""+imin;
				}
				
				if(sec<10){
					time = time+":0"+sec;
				}else{
					time = time+":"+sec;
				}
			}
			
			if(tag!=null&&tag.equals("bz")){
				
				if(sj<bgtimetmp){
					time = time + "/" + bgtime;
					tv_time.setText(time);
				}else{
					starting = false;
					bz = true;
				}
				
			}else{
				tv_time.setText(time);
			}
			
        }
        
        @Override
		protected void onPostExecute(Void result){
  
        }
		@Override
		protected void onPreExecute(){
  
        }
           
    }
	
	/**
	 * 解码Mp3到PCM
	 * @return
	 */
	public native int decodeMp3ToPCM(String mp3File, String mp3PCM);
	
	public native int decodeMp3ToPCM2(String mp3File, String mp3PCM);
	
	public int writeCount(int count){
		Log.e(getClass().getName(), "writeCount-->>"+count);
		return count;
	}
	
	public int writeCovertCount(int count){
		Log.e(getClass().getName(), "writeCovertCount-->>"+count);
		return count;
	}
	
	/**
	 * 合并mp3PCM与sourcePCM
	 * @return
	 */
	public native int mix2PCMToPCM(String sourcePCM, String mp3PCM, String mixPCM);
	public native int mix2PCMToPCM2(String sourcePCM, String mp3PCM, String mixPCM);
	
	public void savePCMToMp3(){
		 int bufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat); 
		SimpleLame.convert(filePath+"pcm/mix.pcm", filePath+"record/"+"mix.mp3", bufferSize);
	}
	/**
	 * 
	 * @return
	 */
	private boolean saveRecord(){
		
		//初始化输入输出流
		//开通输出流到指定的文件    
        try {
			DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filePath+"pcm/mix.pcm")));
			  //定义输入流，将音频写入到AudioTrack类中，实现播放    
	        DataInputStream disRecord = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath+"source.pcm")));
	        //背景音定义输入流，将音频写入到AudioTrack类中，实现播放    
	        DataInputStream disMp3 = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath+"mp3.pcm")));
			//读取Mp3-->PCM
	        
	        
	        
			//读取录音的PCM
			//写入合音文件
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
		return true;
	}

	 class PlayTask extends AsyncTask<Void, Integer, Void>{    
	        @Override   
	        protected Void doInBackground(Void... arg0) {    
	            int bufferSize = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat); 
//	            short[] buffer = new short[bufferSize/4];
//	            short[] bufferfre = new short[bufferSize/4];
//	            short[] bufferBg = new short[bufferSize/4];
	            byte[] bufferBg = new byte[bufferSize];
	            
	            try {    
	            	
	            	//开通输出流到指定的文件    
//	                DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filePath+"mix.pcm")));  
	                //定义输入流，将音频写入到AudioTrack类中，实现播放    
//	                DataInputStream disfre = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath+"source.pcm")));
	                //背景音定义输入流，将音频写入到AudioTrack类中，实现播放    
//	                DataInputStream disBg = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath+"mp3.pcm")));
	                DataInputStream disBg = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath+"mix.pcm")));
	                
	                //实例AudioTrack    
	                AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfig, audioFormat, bufferSize, AudioTrack.MODE_STREAM);
	                //开始播放    
	                track.play();    
//	                WriteAmrFileHeader(dos);
	                //由于AudioTrack播放的是流，所以，我们需要一边播放一边读取    
	                while(playing){    
	                   /* int i = 0;    
	                    while(disfre.available()>0 && i<bufferfre.length){   
	                    	bufferfre[i] = disfre.readShort();
	                        bufferBg[i] = disBg.readShort();
	                    	byte[] buffer2 = new byte[2];
	                    	disBg.read(buffer2);
	                    	bufferBg[i] = RingUtil.getShort(buffer2);
	                        buffer[i] = (short)((bufferfre[i] + bufferBg[i])/2);
	                        if(buffer[i]!=0){
	                        	dos.write(RingUtil.getBytes(buffer[i]));
	                            dos.flush();
	                            System.out.println("写入WAV数据完成");
	                        }
	                        i++;    
	                    }*/
	                	int read = disBg.read(bufferBg);
	                	
	                	if(read==-1){
	                		playing = false;
	                		break;
	                	}
	                	
	                    //然后将数据写入到AudioTrack中    
	                    track.write(bufferBg, 0, bufferBg.length);   
	                }    
	                
//	                wavUtil.ReadWavHead(path+"/baibian/古筝回家.wav");
	                //播放结束    
	                track.stop();    
//	                disfre.close(); 
	                disBg.close();
//	                dos.close();
	            } catch (Exception e) {    
	                // TODO: handle exception    
	            	e.printStackTrace();
	            }    
	            return null;    
	        }    
	 }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_BACK){
			starting = false;
			if(mPlayer!=null&&mPlayer.isPlaying()){
				mPlayer.stop();
			}
		}
		
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		Log.d(this.getClass().getName(), "onDestroy");
		
		starting = false;
		/*//关闭录音
		if(audioRecord!=null){
			
			if(audioRecord.getState()==AudioRecord.STATE_INITIALIZED){
				audioRecord.stop();
				audioRecord.release();
			}
		}*/
		
		if(mPlayer!=null&&mPlayer.isPlaying()){
			mPlayer.stop();
		}
	}

}
